var express = require('express');
var router = express.Router();
var User = require('../models/users');
var Group = require('../models/group');
var util = require('../util/util.js');
var Answer = require('../models/answer');
var ObjectID = require('mongodb').ObjectID;
// 查找队伍下的问题
router.get('/getAqList', function (req, res, next) {
  let { groupId } = req.query;
  Group.findOne({ _id: groupId }).then(groupInfo => {
    let answerIdArr = groupInfo.answerIdArr
    let arr = [];
    console.log('answerIdArr', answerIdArr, answerIdArr.length)
    if (answerIdArr.length > 0) {
      // 当队伍内有问题时
      answerIdArr.forEach(item => {
        arr.push({ '_id': new ObjectID(item) })
      });
      Answer.find({ $or: arr }).then(aqList => {
        res.json({
          status: '0',
          data: aqList
        })
      })
    } else {
      res.json({
        status: '0',
        data: []
      })
    }
  }).catch(err => {
    console.log('这也执行了？？？')
    res.json({
      status: '1',
      msg: err
    })
  })
});
// 队伍下添加问题
router.post('/addAq', function (req, res, next) {
  let { userId, groupId, token, answerTitle, answerContent, avatarUrl, nickName } = req.body;
  let params = {
    userId,
    groupId,
    answerTitle,
    avatarUrl,
    nickName,
    answerContent
  }

  addAq(params).then(newAnswer => {
    if (newAnswer) {
      User.findOne({ token: token }).then(userInfo => {
        userInfo.aqArr.push(newAnswer._id)
        userInfo.save()
      })
      // answerIdArr
      Group.findOne({ _id: groupId }).then(groupInfo => {
        groupInfo.answerIdArr.push(newAnswer._id)
        groupInfo.save()
      })
      res.json({
        status: '0',
        data: newAnswer
      })
    }
  }).catch(err => {
    res.json({
      status: '1',
      msg: err
    })
  })
})
// 创建新问题函数
function addAq (data) {
  return new Promise((resolve, reject) => {
    var userIdArr = [];
    var answerDate = util.nowYMD();
    var answerTime = util.nowHM();
    userIdArr.push(data.userId);
    var answer = new Answer({
      userId: data.userId,
      groupId: data.groupId,
      answerTitle: data.answerTitle,
      answerContent: data.answerContent,
      nickName: data.nickName,
      avatarUrl: data.avatarUrl,
      answerDate: answerDate,
      answerTime: answerTime,
      visiteUsers: userIdArr
    })
    answer.save().then((newAnswerInfo) => {
      resolve(newAnswerInfo);
    }).catch((err) => {
      reject(err);
    })
  })
}
// 根据id查询问题
router.get('/getOneAq', function (req, res, next) {
  let id = req.query.id;
  Answer.findOne({ _id: id }).then(answerInfo => {
    res.json({
      status: '0',
      data: answerInfo
    })
  }).catch(err => {
    res.json({
      status: '1',
      msg: err
    })
  })
})

module.exports = router;
